package discoveries

import (
	"context"
	"discoveries-rpc/constant"
	pb "discoveries-rpc/proto/articles_srv"
	"fmt"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
)

func client(hand func(client pb.ArticlesClient) error) error {
	service, err := nacos.FindService(constant.ServiceName, constant.GroupName)
	if err != nil {
		return err
	}
	// 1.连接
	conn, err := grpc.Dial(service, grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
	}
	defer conn.Close()
	// 2. 实例化gRPC客户端
	c := pb.NewArticlesClient(conn)
	return hand(c)
}

func ArticlesCreate(in *pb.ArticlesCreateReq) (resp *pb.ArticlesCreateResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ArticlesCreate(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func ArticlesShow(in *pb.ArticlesShowReq) (resp *pb.ArticlesShowResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ArticlesShow(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func ArticlesUpdate(in *pb.ArticlesUpdateReq) (resp *pb.ArticlesUpdateResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ArticlesUpdate(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func ArticlesDelete(in *pb.ArticlesDeleteReq) (resp *pb.ArticlesDeleteResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ArticlesDelete(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func ArticlesList(in *pb.ArticlesListReq) (resp *pb.ArticlesListResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ArticlesList(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func ReadCountRise(in *pb.ReadCountRiseReq) (resp *pb.ReadCountRiseResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.ReadCountRise(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func LikeCountRise(in *pb.LikeCountRiseReq) (resp *pb.LikeCountRiseResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.LikeCountRise(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func LikeCountMinimize(in *pb.LikeCountMinimizeReq) (resp *pb.LikeCountMinimizeResp, err error) {
	return resp, client(func(client pb.ArticlesClient) error {
		resp, err = client.LikeCountMinimize(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}
